<template>
    <div style="margin: 50px auto">
  
      <div>
        <ul>
          <li v-for="(item, index) in products" :key="item.id">
            <input type="checkbox" v-model="item.checked" />
            <span>{{ item.name }}</span>
            <span>{{ item.price }}</span>
            <button @click="add(index)">+</button>
            <a>{{ item.count }}</a>
            <button @click="minus(index)">-</button>
            <button @click="del(index)">delete</button>
          </li>
        </ul>
        <div>
          <input type="checkbox" @change="handleChange" v-model="isAllSel" />
          <span>已选({{ selNum }})</span>
          <span>总价¥：{{ totalPrice }}</span>
          <button :disabled="!selNum">结算</button>
        </div>
        <div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed, watch } from "vue";
  
  //初始值
  let isAllSel = ref(false);
  
  let products = ref([
    { id: 1001, name: "iphone16", price: 10000 },
    { id: 1002, name: "ps5", price: 5000 },
    { id: 1003, name: "外星人电脑", price: 20000 },
    { id: 1004, name: "口红", price: 200 },
  ]);
  
  // +
  const add = (index) => {
    //数组中指定索引位置（index）的对象的 count 属性值。
    products.value[index].count++;
  };
  // -
  const minus = (index) => {
    let num = products.value[index].count;
    if (num > 1) {
      products.value[index].count--;
    }
  };
  // delete
  const del = (index) => {
    //splice(开始元素，删除元素)
    products.value.splice(index, 1);
  };
  
  // 已选商品
  let selNum = computed(() => products.value.filter((item) => item.checked).length);
  
  //总价
  const totalPrice = computed(() => {
    let total = 0;
    products.value
      .filter((item) => item.checked)
      .forEach((item) => {
        total += item.count * item.price;
      });
    return total;
  });
  
  //全选 遍历数组。将元素的checked属性设置为isAllSel.value的值。
  const handleChange = () => {
    products.value.forEach((item) => (item.checked = isAllSel.value));
  };
  
  //监听每一个数据的checked属性
  watch(
    () => products.value.map((item) => item.checked),
    () => {
      if (selNum.value == products.value.length) {
        isAllSel.value = true;
      } else {
        isAllSel.value = false;
      }
    }
  );
  
  onMounted(() => {
    // 将 item 的 count 属性设置为 1。
    // 将 item 的 checked 属性设置为 false。
    products.value.forEach((item) => {
      item.count = 1;
      item.checked = false;
    });
  });
  </script>
  
  <style scoped>
  span,
  button {
    margin: 0 10px;
    width: 100px;
    display: inline-block;
  }
  </style>
  